/*****************************************************************************************
* Copyright (c) 2024 cxhgt
* E-mail: cxhgt@qq.com
* All rights reserved.
* This software is provided "as is", without warranty of any kind, express or implied.
*****************************************************************************************/

#include <thread>
#include <iostream>

#include "PocketSurvival/ServerRun.h"
#include <assert.h>
#include "spdlog/spdlog.h"

using namespace PocketSurvival;

#ifdef _WIN32
#include <windows.h>
#include <dbghelp.h>

std::string GbkToUtf8(const char *src_str)
{
	int len = MultiByteToWideChar(CP_ACP, 0, src_str, -1, NULL, 0);
	wchar_t* wstr = new wchar_t[len + 1];
	memset(wstr, 0, len + 1);
	MultiByteToWideChar(CP_ACP, 0, src_str, -1, wstr, len);
	len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
	char* str = new char[len + 1];
	memset(str, 0, len + 1);
	WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, len, NULL, NULL);
	std::string strTemp = str;
	if (wstr) delete[] wstr;
	if (str) delete[] str;
	return strTemp;
}

std::string Utf8ToGbk(const char *src_str)
{
	int len = MultiByteToWideChar(CP_UTF8, 0, src_str, -1, NULL, 0);
	wchar_t* wszGBK = new wchar_t[len + 1];
	memset(wszGBK, 0, len * 2 + 2);
	MultiByteToWideChar(CP_UTF8, 0, src_str, -1, wszGBK, len);
	len = WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, NULL, 0, NULL, NULL);
	char* szGBK = new char[len + 1];
	memset(szGBK, 0, len + 1);
	WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, szGBK, len, NULL, NULL);
	std::string strTemp(szGBK);
	if (wszGBK) delete[] wszGBK;
	if (szGBK) delete[] szGBK;
	return strTemp;
}


// 打印堆栈信息的实现
void PrintStackTrace(EXCEPTION_POINTERS* exp) {
    // 初始化符号引擎
    SymInitialize(GetCurrentProcess(), nullptr, TRUE);

    // 获取堆栈信息
    CONTEXT* context = exp->ContextRecord;
    STACKFRAME64 stackFrame;
    memset(&stackFrame, 0, sizeof(STACKFRAME64));

    DWORD machineType = IMAGE_FILE_MACHINE_AMD64; // 64 位架构
    stackFrame.AddrPC.Offset = context->Rip; // RIP 寄存器保存了当前指令指针
    stackFrame.AddrPC.Mode = AddrModeFlat;
    stackFrame.AddrFrame.Offset = context->Rsp; // RSP 寄存器保存了当前堆栈指针
    stackFrame.AddrFrame.Mode = AddrModeFlat;
    stackFrame.AddrStack.Offset = context->Rsp; // 使用 RSP 作为堆栈指针
    stackFrame.AddrStack.Mode = AddrModeFlat;

    while (StackWalk64(
        machineType,
        GetCurrentProcess(),
        GetCurrentThread(),
        &stackFrame,
        context,
        nullptr,
        SymFunctionTableAccess64,
        SymGetModuleBase64,
        nullptr)) {
        // 获取符号名称
        char symbolBuffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR)];
        PSYMBOL_INFO symbol = (PSYMBOL_INFO)symbolBuffer;
        symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
        symbol->MaxNameLen = MAX_SYM_NAME;

        DWORD64 displacement = 0;
        if (SymFromAddr(GetCurrentProcess(), stackFrame.AddrPC.Offset, &displacement, symbol)) {
            std::cout << "    " << symbol->Name << "()" << std::endl;
        } else {
            std::cout << "    <unknown symbol>" << std::endl;
        }
    }

    SymCleanup(GetCurrentProcess());
    // system("pause");
}

LONG WINAPI ExceptionHandler(EXCEPTION_POINTERS* exp) {
    std::cerr << "Unhandled exception occurred. Pausing the program." << std::endl;

    // 可以在这里实现暂停逻辑，例如等待用户输入以继续或者启动调试器
    PrintStackTrace(exp);
    
    std::cout << "Press Enter to continue..." << std::endl;
    std::cin.get();

    // 返回 EXCEPTION_CONTINUE_SEARCH 继续搜索其他异常处理器，或者直接返回 EXCEPTION_EXECUTE_HANDLER 终止程序
    return EXCEPTION_EXECUTE_HANDLER;
}

#endif


void ThreadTest()
{
    while(true)
    {
        std::string message;
        std::getline(std::cin, message);

    #if _WIN32
        message = GbkToUtf8(message.c_str());
    #endif

        if(message.length() > 0)
        {
            if(message == "clear")
            {
    #if _WIN32
                system("cls");
    #else
                system("clear");
    #endif
            }
            else if(message == "stop")
            {
                PocketSurvival::Stop();
                return;
            }
            else
            {
                PocketSurvival::TerminalMessage(message);
            }
        }
    }
}


int main(int argc, char *argv[])
{
    spdlog::details::registry::instance();

#if _WIN32
    printf("\xC8\xF4\xB3\xF6\xCF\xD6\xD6\xD0\xCE\xC4\xC2\xD2\xC2\xEB\xA3\xAC\xC7\xEB\xB0\xB2\xD7\xB0\x50\x6F\x77\x65\x72\x53\x68\x65\x6C\x6C\x37\xBC\xB4\xBF\xC9\xBD\xE2\xBE\xF6 \n");
    system("pwsh -Command $OutputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding");


    SetUnhandledExceptionFilter(ExceptionHandler);

    // // 设置异常处理器
    // SetUnhandledExceptionFilter([](EXCEPTION_POINTERS* exp) -> LONG {
    //     std::cerr << "Unhandled exception occurred." << std::endl;
    //     PrintStackTrace(exp);
    //     return EXCEPTION_EXECUTE_HANDLER;
    // });

#endif

    std::thread thread(ThreadTest);

    PocketSurvival::Run();

    thread.join();
    printf("PSTerminal end");


    return 0;
}